<script setup lang="js">
import { ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { startElementPicker } from './element-picker.js'
import { executeCrawl, autoDetectPageStructure } from './crawler.js'
import { saveConfig, loadConfig, getConfigKey } from './config-manager.js'



const options = [
  {
    value: 'https://www.court.gov.cn/fabu/gengduo/17.html',
    label: '最高法-司法文件发布',
  },
]

// 为最高法网站预设的配置
const presetConfigs = {
  'www.court.gov.cn': {
    listSelector: '.sec_list li',  // 使用正确的内容列表选择器
    titleSelector: 'a',
    titleLinkSelector: 'a',
    dateSelector: 'i.date',
    nextPageSelector: '.next a',
    maxPages: 3
  }
}

const form = ref({
  url: options[0].value,
  listSelector: '',
  titleSelector: '',
  titleLinkSelector: '',
  dateSelector: '',
  nextPageSelector: '',
  maxPages: 3,
  customSelectors: []
})

const dialogVisible = ref(false)
const crawlResult = ref(null)
const activeField = ref('')
const crawling = ref(false)
const saving = ref(false)
const loading = ref(false)
const hasConfig = ref(false)
const detecting = ref(false)

const setActiveField = (fieldName) => {
  activeField.value = fieldName
}

const setActiveCustomField = (index) => {
  activeField.value = `customSelectors.${index}.value`
}

const addCustomSelector = () => {
  form.value.customSelectors.push({ name: '', value: '' })
}

const removeCustomSelector = (index) => {
  form.value.customSelectors.splice(index, 1)
}

// 保存配置
const saveCurrentConfig = async () => {
  if (saving.value) return

  try {
    saving.value = true
    await saveConfig(form.value.url, form.value)
    hasConfig.value = true
    ElMessage.success('配置已保存')
  } catch (error) {
    console.error('保存配置失败:', error)
    ElMessage.error('保存配置失败: ' + error.message)
  } finally {
    saving.value = false
  }
}

// 加载配置
const loadCurrentConfig = async (showMessage = false) => {
  if (loading.value) return false

  try {
    loading.value = true
    const config = await loadConfig(form.value.url)

    if (config) {
      // 保留URL，加载其他配置
      form.value.listSelector = config.listSelector || ''
      form.value.titleSelector = config.titleSelector || ''
      form.value.titleLinkSelector = config.titleLinkSelector || ''
      form.value.dateSelector = config.dateSelector || ''
      form.value.nextPageSelector = config.nextPageSelector || ''
      form.value.maxPages = config.maxPages || 3
      form.value.customSelectors = config.customSelectors || []

      hasConfig.value = true
      if (showMessage) {
        ElMessage.success('配置已加载')
      }
      return true
    } else {
      hasConfig.value = false
      if (showMessage) {
        ElMessage.info('该网址暂无保存的配置')
      }
      return false
    }
  } catch (error) {
    console.error('加载配置失败:', error)
    hasConfig.value = false
    if (showMessage) {
      ElMessage.error('加载配置失败: ' + error.message)
    }
    return false
  } finally {
    loading.value = false
  }
}

// 手动加载配置
const manualLoadConfig = async () => {
  await loadCurrentConfig(true)
}

// 应用预设配置
const applyPresetConfig = (url) => {
  try {
    const hostname = new URL(url).hostname
    const preset = presetConfigs[hostname]
    if (preset) {
      Object.assign(form.value, preset)
      console.log('应用预设配置:', preset)
      return true
    }
  } catch (e) {
    console.log('无法解析URL或无预设配置')
  }
  return false
}

// 监听URL变化，自动加载配置（不显示消息）
watch(() => form.value.url, async (newUrl) => {
  if (newUrl) {
    // 先尝试加载保存的配置
    const loaded = await loadCurrentConfig(false)
    // 如果没有保存的配置，尝试应用预设配置
    if (!loaded) {
      applyPresetConfig(newUrl)
    }
  }
}, { immediate: true })

// 跳转到目标页面
const goToPage = async () => {
  await chrome.tabs.create({ url: form.value.url })
}

// 智能识别页面结构
const smartDetect = async () => {
  if (detecting.value) return

  try {
    detecting.value = true
    const [tab] = await chrome.tabs.query({ active: true, currentWindow: true })

    // 检查标签页和URL
    if (!tab || !tab.url) {
      ElMessage.error('无法获取当前页面信息，请刷新页面后重试')
      return
    }

    // 检查是否在目标页面
    try {
      const targetHostname = new URL(form.value.url).hostname
      if (!tab.url.includes(targetHostname)) {
        ElMessage.warning(`请先跳转到目标页面 (${targetHostname})`)
        return
      }
    } catch (urlError) {
      ElMessage.error('目标URL格式不正确')
      return
    }

    // 执行智能识别
    const result = await chrome.scripting.executeScript({
      target: { tabId: tab.id },
      func: autoDetectPageStructure
    })

    const detectedConfig = result[0].result

    if (detectedConfig) {
      // 更新表单配置
      if (detectedConfig.listSelector) form.value.listSelector = detectedConfig.listSelector
      if (detectedConfig.titleSelector) form.value.titleSelector = detectedConfig.titleSelector
      if (detectedConfig.titleLinkSelector) form.value.titleLinkSelector = detectedConfig.titleLinkSelector
      if (detectedConfig.dateSelector) form.value.dateSelector = detectedConfig.dateSelector
      if (detectedConfig.nextPageSelector) form.value.nextPageSelector = detectedConfig.nextPageSelector

      ElMessage.success('智能识别完成！已自动填充选择器')
      console.log('智能识别结果:', detectedConfig)
    } else {
      ElMessage.warning('未能识别到合适的页面结构')
    }
  } catch (error) {
    console.error('智能识别失败:', error)
    ElMessage.error('智能识别失败: ' + error.message)
  } finally {
    detecting.value = false
  }
}



// 快速修复 - 直接使用最高法的正确配置
const quickFix = () => {
  form.value.listSelector = '.sec_list li'
  form.value.titleSelector = 'a'
  form.value.titleLinkSelector = 'a'
  form.value.dateSelector = 'i.date'
  form.value.nextPageSelector = '.next a'
  ElMessage.success('已应用最高法网站的正确配置')
}

// 开始爬取
const startCrawling = async () => {
  if (crawling.value) return

  try {
    crawling.value = true
    const [tab] = await chrome.tabs.query({ active: true, currentWindow: true })

    // 检查标签页和URL
    if (!tab || !tab.url) {
      ElMessage.error('无法获取当前页面信息，请刷新页面后重试')
      return
    }

    // 检查是否在目标页面
    try {
      const targetHostname = new URL(form.value.url).hostname
      if (!tab.url.includes(targetHostname)) {
        ElMessage.warning(`请先跳转到目标页面 (${targetHostname})`)
        return
      }
    } catch (urlError) {
      ElMessage.error('目标URL格式不正确')
      return
    }

    // 检查必要的选择器
    if (!form.value.listSelector) {
      ElMessage.warning('请先配置列表选择器或使用智能识别')
      return
    }

    console.log('开始爬取，配置:', form.value)

    // 执行爬取
    const result = await executeCrawl(form.value)

    if (result && result.items) {
      crawlResult.value = result
      dialogVisible.value = true
      console.log('爬取结果:', crawlResult.value)
      ElMessage.success(`爬取完成！共获得 ${result.totalItems || result.items.length} 条数据`)
    } else {
      ElMessage.warning('爬取完成，但未获得有效数据')
    }
  } catch (error) {
    console.error('爬取失败:', error)
    ElMessage.error('爬取失败: ' + (error.message || '未知错误'))
  } finally {
    crawling.value = false
  }
}





// 处理元素选择消息
chrome.runtime.onMessage.addListener((msg) => {
  if(msg.type === 'elementSelected') {
    if (activeField.value) {
      // 处理自定义选择器字段
      if (activeField.value.startsWith('customSelectors.')) {
        const match = activeField.value.match(/customSelectors\.(\d+)\.value/)
        if (match) {
          const index = parseInt(match[1])
          form.value.customSelectors[index].value = msg.selector
        }
      } else {
        // 处理普通字段
        form.value[activeField.value] = msg.selector
      }

      activeField.value = ''
      console.log('选择器已设置:', msg.selector)
    }
  }
})
</script>

<template>
  <main>
    <h3>文章爬取配置</h3>

    <el-alert
      title="使用说明"
      type="info"
      :closable="false"
      style="margin-bottom: 20px;"
    >
      <div style="font-size: 13px; line-height: 1.5;">
        <p><strong>🚀 使用方式：</strong></p>
        <p><strong>方式1（推荐）：</strong>点击"智能识别"自动分析页面结构</p>
        <p><strong>方式2（备用）：</strong>如果识别不准确，点击"快速修复"使用预设配置</p>
        <p><strong>方式3（手动）：</strong>手动选择列表容器和内容元素</p>
        <p>💡 配置完成后直接"开始爬取"即可获取数据</p>
      </div>
    </el-alert>
    
    <el-form :model="form" label-width="120px">
      <el-form-item label="目标网址">
        <div style="display: flex; flex-direction: column; gap: 8px;">
          <el-select v-model="form.url" placeholder="请选择目标网址" style="width: 250px">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
          <div style="display: flex; justify-content: flex-end;">
            <el-tag v-if="hasConfig" type="success" size="small">已有配置</el-tag>
            <el-tag v-else type="info" size="small">无配置</el-tag>
          </div>
        </div>
      </el-form-item>
      
      <el-form-item label="列表选择器">
        <div style="display: flex; gap: 10px;">
          <el-input v-model="form.listSelector" placeholder="可选：选择列表容器（如：li、.item）" />
          <el-button @click="setActiveField('listSelector'); startElementPicker()" size="small">选择元素</el-button>
          <el-button @click="quickFix" size="small" type="success">快速修复</el-button>
        </div>
      </el-form-item>

      <el-form-item label="标题选择器">
        <div style="display: flex; gap: 10px;">
          <el-input v-model="form.titleSelector" placeholder="选择标题元素（如：h3、.title、a）" />
          <el-button @click="setActiveField('titleSelector'); startElementPicker()" size="small">选择元素</el-button>
        </div>
      </el-form-item>

      <el-form-item label="标题链接选择器">
        <div style="display: flex; gap: 10px;">
          <el-input v-model="form.titleLinkSelector" placeholder="选择链接元素（如：a、.link）" />
          <el-button @click="setActiveField('titleLinkSelector'); startElementPicker()" size="small">选择元素</el-button>
        </div>
      </el-form-item>

      <el-form-item label="时间选择器">
        <div style="display: flex; gap: 10px;">
          <el-input v-model="form.dateSelector" placeholder="选择时间元素（如：.date、.time）" />
          <el-button @click="setActiveField('dateSelector'); startElementPicker()" size="small">选择元素</el-button>
        </div>
      </el-form-item>

      <el-form-item label="下一页选择器">
        <div style="display: flex; gap: 10px;">
          <el-input v-model="form.nextPageSelector" placeholder="选择下一页按钮（如：.next）" />
          <el-button @click="setActiveField('nextPageSelector'); startElementPicker()" size="small">选择元素</el-button>
        </div>
      </el-form-item>

      <el-form-item label="最大翻页数">
        <el-input-number v-model="form.maxPages" :min="1" :max="10" placeholder="最多爬取几页" />
        <span style="margin-left: 10px; color: #666; font-size: 12px;">建议不超过5页，避免过度请求</span>
      </el-form-item>
      
      <el-form-item label="自定义选择器">
        <el-button @click="addCustomSelector">添加自定义选择器</el-button>
        <div v-for="(selector, index) in form.customSelectors" :key="index" class="custom-selector" style="margin-top: 10px;">
          <div style="display: flex; gap: 10px; align-items: center;">
            <el-input v-model="selector.name" placeholder="字段名" style="width: 120px" />
            <el-input v-model="selector.value" placeholder="CSS选择器" style="flex: 1" />
            <el-button @click="setActiveCustomField(index); startElementPicker()" size="small">选择元素</el-button>
            <el-button type="danger" @click="removeCustomSelector(index)" size="small">删除</el-button>
          </div>
        </div>
      </el-form-item>
      
      <el-form-item>
        <div style="display: flex; gap: 10px; flex-wrap: wrap;">
          <el-button @click="goToPage">跳转页面</el-button>
          <el-button
            type="warning"
            @click="smartDetect"
            :loading="detecting"
            :disabled="detecting"
          >
            {{ detecting ? '识别中...' : '🔍 智能识别' }}
          </el-button>
          <el-button
            type="info"
            @click="manualLoadConfig"
            :loading="loading"
            :disabled="loading"
          >
            {{ loading ? '加载中...' : '加载配置' }}
          </el-button>
          <el-button
            type="success"
            @click="saveCurrentConfig"
            :loading="saving"
            :disabled="saving"
          >
            {{ saving ? '保存中...' : '保存配置' }}
          </el-button>
          <el-button
            type="primary"
            @click="startCrawling"
            :loading="crawling"
            :disabled="crawling"
          >
            {{ crawling ? '爬取中...' : '开始爬取' }}
          </el-button>
        </div>
      </el-form-item>
    </el-form>
    
    <el-dialog v-model="dialogVisible" title="爬取结果" width="80%">
      <div v-if="crawlResult">
        <p><strong>
          共爬取 {{ crawlResult.totalPages || 1 }} 页，
          找到 {{ crawlResult.totalItems || crawlResult.items?.length || 0 }} 条数据
        </strong></p>
        <div v-for="(item, index) in crawlResult.items" :key="index" style="border: 1px solid #eee; padding: 10px; margin: 10px 0;">
          <div v-if="item.title"><strong>标题:</strong> {{ item.title }}</div>
          <div v-if="item.titleLink">
            <strong>链接:</strong>
            <a :href="item.titleLink" target="_blank" style="color: #409eff;">{{ item.titleLink }}</a>
          </div>
          <div v-if="item.date"><strong>时间:</strong> {{ item.date }}</div>
          <div v-for="(value, key) in item" :key="key">
            <span v-if="!['title', 'titleLink', 'date'].includes(key)">
              <strong>{{ key }}:</strong> {{ value }}
            </span>
          </div>
        </div>
        <div v-if="crawlResult.nextPage">
          <strong>下一页:</strong>
          <a :href="crawlResult.nextPage" target="_blank" style="color: #409eff;">{{ crawlResult.nextPage }}</a>
        </div>
      </div>
      <template #footer>
        <el-button @click="dialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </main>
</template>

<style>
main {
  padding: 20px;
}

h3 {
  color: #333;
  font-size: 18px;
}

.custom-selector {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 10px;
  background-color: #fafafa;
}

.el-button {
  white-space: nowrap;
}
</style>
